﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;

namespace DevCow.Mashups.Blocks.Samples
{
    public class TwitterClass
    {
        public int lastMessageID { get; set; }
        private string formatString = "http://twitter.com{0}.json?{1}";
        private List<string> args = new List<string>();

        private TwitterStatus[] CallWebService(string method, int number, List<string> parms, _parseMethod parseMethod)
        {
            if(null == parms)
            {
                parms = new List<string>();
            }

            parms.Add("count=" + number);

            string url = String.Format(formatString, method,String.Join("&",parms.ToArray()));
         
            string results;
            HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;

            if (null == request)
            {
                throw new ApplicationException("Could not make HttpWebRequest");
            }
            using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream()))
            {
                results = sr.ReadToEnd();
            }
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            var x = serializer.DeserializeObject(results);
            return parseMethod(x, number);
        }

        public TwitterStatus[] getLatestPosts(int number)
        {
            if (this.lastMessageID > 0)
            {
                args.Add("since_id=" + this.lastMessageID);
            }
            return CallWebService("/statuses/public_timeline", number, args, _parsePosts);
        }

        public TwitterStatus[] getLatestUserPosts(int userID, int number)
        {
            if (this.lastMessageID > 0)
            {
                args.Add("since_id=" + this.lastMessageID);
            }
            return CallWebService("/status/user_timeline/" + userID, number, args, _parsePosts);
        }

        public TwitterStatus[] getFriends (int userID, int number)
        {
            return CallWebService("/statuses/friends/" + userID, number, null, _parseUsers);
        }

        public delegate TwitterStatus[] _parseMethod(object a, int b);

        private TwitterStatus[] _parsePosts(object rawPosts, int number)
        {
            var users = new List<TwitterStatus>();
            if (rawPosts.GetType().IsArray)
            {
                var y = (System.Object[])rawPosts;
                foreach (Dictionary<string, object> post in y)
                {
                    //create twitter status
                    Dictionary<string, object> user = null;
                    if (post.ContainsKey("user"))
                    {
                        user = (Dictionary<string, object>)post["user"];
                    }

                    var twitterStatus = new TwitterStatus(GetJSONValue(post, "id"), GetJSONValue(post, "text"),
                        GetJSONValue(post, "created_at"), GetJSONValue(user, "id"), GetJSONValue(user, "screen_name"),
                        GetJSONValue(user, "name"), GetJSONValue(user, "location"), GetJSONValue(user, "description"),
                        GetJSONValue(user, "profile_image_url"), GetJSONValue(user, "url"));
                    users.Add(twitterStatus);

                    var messageID = int.Parse(GetJSONValue(post,"id"));
                    if (messageID > this.lastMessageID)
                    {
                        this.lastMessageID = messageID;
                    }

                }
            }
            return users.ToArray();
 
        }

        private TwitterStatus[] _parseUsers(object rawUsers, int number)
        {
            var users = new List<TwitterStatus>();
            if (rawUsers.GetType().IsArray)
            {
                var y = (System.Object[])rawUsers;
                foreach (Dictionary<string, object> user in y)
                {
                    //create twitter status
                    Dictionary<string, object> status = null;
                    if(user.ContainsKey("status"))
                    {
                       status = (Dictionary<string, object>)user["status"];
                    }
                    
                    if(null == status)
                    {
                        status = new Dictionary<string, object>();
                        status.Add("id", null);
                        status.Add("text",null);
                        status.Add("created_at", null);
                    }

                    var twitterStatus = new TwitterStatus(GetJSONValue(status, "id"), GetJSONValue(status, "text"),
                        GetJSONValue(status, "created_at"), GetJSONValue(user,"id"), GetJSONValue(user,"screen_name"),
                        GetJSONValue(user,"name"), GetJSONValue(user,"location"), GetJSONValue(user,"description"),
                        GetJSONValue(user,"profile_image_url"), GetJSONValue(user,"url"));
                    users.Add(twitterStatus);
                }
            }
            return users.ToArray();
        }



        private String GetJSONValue(IDictionary<string, object> user, string key)
        {
            if(user.ContainsKey(key))
            {
                var property = user[key];
                if(null != property)
                {
                    return property.ToString();
                }
            }
            return null;
        }
    }

    public class TwitterStatus    
    {
        public TwitterStatus(){}
        public TwitterStatus(string messageID, string text, 
            string createdAt, string userID, string screenName, 
            string name, string location, string description, 
            string imageUrl, string url)
        {
            this.messageID = messageID;
            this.text = text;
            this.createdAt = createdAt;
            this.userID = userID;
            this.screenName = screenName;
            this.name = name;
            this.location = location;
            this.description = description;
            this.imageUrl = imageUrl;
            this.url = url;
        }
        public string messageID { get; set; }  
        public string text {get;set;}
        public string createdAt {get;set;}
        public string userID {get;set;}
        public string screenName {get;set;}
        public string name {get;set;}
        public string location {get;set;}
        public string description {get;set;}
        public string imageUrl {get;set;}
        public string url {get;set;}

        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append("<img border='0' src='" + this.imageUrl + "' >" + "<br>");
            sb.Append("text: " + this.text + "<br>");
            sb.Append("createdAt: " + this.createdAt + "<br>");
            sb.Append("name: " + this.name + "<br>");
            sb.Append("screenName: " + this.screenName + "<br>");
            sb.Append("location: " + this.location + "<br>");
            sb.Append("description: " + this.description + "<br>");
            sb.Append("<a href='" + this.url + "'>link</a>" + "<br>");
            sb.Append("<p/>");
            return sb.ToString();
        }
    }
}